package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.SysWechatListener;
import com.settlement.system.model.dto.FileInfo;
import com.settlement.system.model.entity.SysWechat;
import com.settlement.system.model.form.SysWechatForm;
import com.settlement.system.model.query.SysWechatQuery;
import com.settlement.system.model.vo.SysWechatImportVo;
import com.settlement.system.service.OssService;
import com.settlement.system.service.SysWechatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 管理员微信表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-03-11
 */
@RestController
@RequestMapping("/api/v1/wechat")
@RequiredArgsConstructor
public class SysWechatController {

    private final SysWechatService sysWechatService;

    private final OssService ossService;

    @Operation(summary = "管理员微信表分页", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysWechat> getPage(@ParameterObject SysWechatQuery queryParams) {
        Page<SysWechat> result = sysWechatService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存管理员微信表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:wechat:save')")
    public Result<?> saveSysWechat(@RequestBody @Valid SysWechatForm sysWechatForm) {
        boolean result = sysWechatService.saveSysWechat(sysWechatForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取管理员微信表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysWechatForm> getSysWechatFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysWechatForm sysWechat = sysWechatService.getSysWechatFormData(id);
        return Result.success(sysWechat);
    }

    @Operation(summary = "删除管理员微信表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:wechat:delete')")
    public Result<?> deleteSysWechat(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysWechatService.deleteSysWechat(ids);
        return Result.judge(result);
    }

    @Operation(summary = "启用管理员微信表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/enable/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:wechat:save')")
    public Result<?> enable(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysWechatService.enable(ids);
        return Result.judge(result);
    }

    @Operation(summary = "禁用管理员微信表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/disable/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:wechat:save')")
    public Result<?> disable(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysWechatService.disable(ids);
        return Result.judge(result);
    }

    @Operation(summary = "管理员微信表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysWechatImport")
    @PreAuthorize("@ss.hasPerm('sys:wechat:import')")
    @PreventDuplicateSubmit
    public Result<?> sysWechatImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysWechatListener listener = new SysWechatListener();
        EasyExcelFactory.read(file.getInputStream(), SysWechatImportVo.class, listener).sheet(0).doRead();
        List<SysWechatImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        sysWechatService.importData(list);
        return Result.success();
    }

    @Operation(summary = "添加管理员微信", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysWechatUser")
    @PreAuthorize("@ss.hasPerm('sys:wechat:sysWechatUser')")
    @PreventDuplicateSubmit
    public Result<?> sysWechatUser(@RequestParam String userName, @RequestParam("file") MultipartFile file) throws Exception {
        FileInfo fileInfo = ossService.uploadFile(file);
        SysWechat sysWechat = new SysWechat();
        sysWechat.setFilePath(fileInfo.getName());
        sysWechat.setUserName(userName);
        sysWechatService.getBaseMapper().insert(sysWechat);
        return Result.success();
    }

    @Operation(summary = "导出管理员微信表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:wechat:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "管理员微信表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysWechatImportVo> sysWechatList = sysWechatService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysWechatImportVo.class).sheet("管理员微信表").doWrite(sysWechatList);
    }
}

